package com.example.tkmybatisspringboot.service.impl;
import com.example.tkmybatisspringboot.mapper.StudentMapper;
import com.example.tkmybatisspringboot.pojo.Student;
import com.example.tkmybatisspringboot.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;


@Service
public class StudentServiceImpl implements StudentService {


    @Autowired
    private StudentMapper studentMapper;

    public Example createExample(Student student) {
        // 自定义条件搜索对象 Example
        Example example = new Example(Student.class);
        Example.Criteria criteria = example.createCriteria(); //条件构造器

        if (student != null) {
            if (!StringUtils.isEmpty(student.getName())) {
                criteria.andLike("name", '%' + student.getName() + '%');
            }
        }
        return example;
    }

    @Override
    public List<Student> findAll() {
        return studentMapper.selectAll();
    }

    @Override
    public List<Student> findList(Student Student) {
        Example example = createExample(Student);
        example.orderBy("create_time");
        return studentMapper.selectByExample(example);
    }

    @Override
    public Student findById(Integer id) {
        return studentMapper.selectByPrimaryKey(id);
    }

    /**
     * 分页查询
     * @param page  当前页
     * @param size  每页显示的条数
     * @return
     */
//    @Override
//    public PageInfo<Student> pageSearch(Integer page, Integer size) {
//        // 分页实现
//        // 后面的查询必须是紧跟集合查询
//        PageHelper.startPage(page, size);
//        // 查询集合
//        List<Student> Students = studentMapper.selectAll();
//        return new PageInfo<Student>(Students);
//    }
//
//    @Override
//    public PageInfo<Student> pageSearchAndCondition(Student Student, Integer page, Integer size) {
//        // 开始分页
//        PageHelper.startPage(page, size);
//        // 搜索数据
//        Example example = createExample(Student);
//        List<Student> list = studentMapper.selectByExample(example);
//        return new PageInfo<Student>(list);
//    }

    /**
     * 增加学生
     * @param Student
     */
    @Override
    public void add(Student Student) {
        // 使用通用 Mapper.insertSelective
        // 方法中但凡带有selective就会忽略空值
        int i = studentMapper.insertSelective(Student);
    }

    /**
     * 根据id修改学生
     * @param Student
     */
    @Override
    public void update(Student Student) {
        // 使用通用mapper.update();
        studentMapper.updateByPrimaryKeySelective(Student);
    }

    /**
     * 根据id删除
     * @param id
     */
    @Override
    public void del(Integer id) {
        studentMapper.deleteByPrimaryKey(id);
    }
}
